﻿using Microsoft.Tools.WindowsInstallerXml.Bootstrapper;

namespace Wix.Win8SetupBootstrapper.ViewModels
{
    public class ConfigurationItemViewModel : ViewModelBase
    {
        private bool _isValueRetreived;
        private string _value;

        public ConfigurationItemViewModel(BootstrapperApplication bootstrapper, string caption, string wixVariable)
            : base(bootstrapper)
        {
            Caption = caption;
            WixVariable = wixVariable;
        }

        public string Caption { get; private set; }

        private string WixVariable { get; set; }

        public string Value
        {
            get
            {
                if (!_isValueRetreived)
                {
                    _value = ReadVariableFromBundle(WixVariable);

                    if (!string.IsNullOrEmpty(_value))
                    {
                        _value = Bootstrapper.Engine.FormatString(_value);
                        _value = _value.Trim('"');

                        WriteVariableToBundle(WixVariable, _value);
                    }

                    _isValueRetreived = true;
                }

                return _value;
            }
            set
            {
                if (_value != value)
                {
                    _value = value;

                    WriteVariableToBundle(WixVariable, _value);
                    OnPropertyChanged();
                }
            }
        }
    }
}